package com.example.suanfa;

import java.util.Arrays;

public class CountSort {
    public static void main(String[] args) {
        int[] arr = {2, 4, 4, 5, 1, 5, 2, 5, 1, 4, 1, 8, 2, 9, 5, 2, 6, 3};
        int[] result = sort(arr);
        System.out.println(Arrays.toString(result));
    }

    static int[] sort(int[] arr) {
        int[] result = new int[arr.length];
        int[] count = new int[10];
        for (int i = 0; i < arr.length; i++) {
            count[arr[i]]++;
        }
        System.out.println(Arrays.toString(count));
//        for (int i=0,j=0; i<count.length; i++){
//            while (count[i]-- >0) { result[j++]=i;}
//        }
        //累加数组 可以保持本来的数组相对顺序不变
        for (int i = 1; i < count.length; i++) {
            count[i] = count[i] + count[i - 1];
        }
        System.out.println(Arrays.toString(count));
        for (int i = arr.length - 1; i >= 0; i--) {
            result[--count[arr[i]]] = arr[i];
        }
        return result;
    }
}
